import {
  isDistanceGreaterThan5Km,
  getTimestampToDay
} from '../../util/index'

Page({
  data: {
    latitude: '',
    longitude: '',
    list: [],
    showList: true,
    name: '',
    phone: '',
    plateNumber: '',
    cargoIndex: null,
    imgPath: '',
    cargoTypes: [
      '沫煤',
      '兰炭',
      '煤焦油'
    ],
    isSubmitting: false
  },
  onLoad() {
    let _this = this
    // 获取用户当前位置
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail: err => {
        console.log(err, '获取位置信息失败')
        wx.showToast({
          title: '获取位置信息失败',
          icon: 'none'
        })
      }
    })
    this.getList()
  },
  onPullDownRefresh() {
    if (this.data.showList) {
      this.getList()
    } else {
      wx.stopPullDownRefresh()
    }
  },

  // 日期格式化函数
  formatDate(d) {
    const date = new Date(d)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  },
  getList() {
    let _this = this
    wx.cloud.callFunction({
      name: 'userSubscribeFun',
      data: {
        type: 'getSubScribeList',
      },
      complete: res => {
        console.log(res, '获取列表---------')
        wx.stopPullDownRefresh()
        if (res.result.code == 200) {
          if (res.result.data.length > 0) {
            _this.setData({
              list: res.result.data.map(d => {
                return {
                  ...d,
                  create_time: _this.formatDate(d.create_time)
                }
              }),
              showList: true
            })
          } else {
            _this.setData({
              showList: false
            })
          }
          return
        }
        wx.showToast({
          title: '获取预约信息失败',
          icon: 'none'
        })
        _this.setData({
          showList: false
        })
      }
    })
  },
  handleUpload() {
    let _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: res => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        console.log(tempFilePath, 12312)
        wx.cloud.uploadFile({
          cloudPath: 'images/' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000) + ".png",
          filePath: tempFilePath,
          success: res => {
            _this.setData({
              imgPath: res.fileID
            })
            console.log(res, '上传成功-----')
          },
          fail: err => {
            console.log(err, '上传失败')
            wx.showToast({
              title: '上传失败，请稍后再试',
              icon: 'none'
            })
          }
        })
      },
      fail: err => {
        wx.showToast({
          title: '上传图片失败',
          icon: 'none'
        })
      }
    })
  },

  hanldePreView(e) {
    const imgPath = e.currentTarget.dataset.img
    wx.previewImage({
      current: 'imgPath', // 当前显示图片的http链接
      urls: [imgPath] // 需要预览的图片http链接列表
    })
  },

  // 表单提交
  formSubmit: function (e) {
    const getCodeTime = wx.getStorageSync('getCodeTime')
    const curToday = getTimestampToDay()
    if (curToday == getCodeTime) {
      wx.showToast({
        title: '今日已经取过号，不可重复取号',
        icon: 'none'
      })
      return
    }
    const {
      name,
      phone,
      plateNumber
    } = e.detail.value;
    const {
      cargoIndex,
      cargoTypes,
      imgPath,
      latitude,
      longitude
    } = this.data;
    const that = this;

    // 验证姓名
    if (!name || name.trim() === '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }

    // 验证手机号
    const phonePattern = /^1[3-9]\d{9}$/;
    if (!phonePattern.test(phone)) {
      wx.showToast({
        title: '请输入有效的手机号码',
        icon: 'none'
      });
      return;
    }

    // 验证车牌号
    const platePattern = /^[\u4e00-\u9fa5][A-Za-z]·\d{5}$/;
    if (!platePattern.test(plateNumber)) {
      wx.showToast({
        title: '请输入正确的车牌号',
        icon: 'none'
      });
      return;
    }

    // 验证货物类型
    if (cargoIndex === null) {
      wx.showToast({
        title: '请选择货物类型',
        icon: 'none'
      });
      return;
    }

    if (!imgPath) {
      wx.showToast({
        title: '请上传图片',
        icon: 'none'
      });
      return;
    }

    // 显示提交中状态
    that.setData({
      isSubmitting: true
    });
    const result = isDistanceGreaterThan5Km(latitude, longitude, '43.709885831015434', '95.03414774259772')
    if (!result) {
      wx.showToast({
        title: '请在指定区域内提交信息',
        icon: 'none'
      })
      this.setData({
        isSubmitting: false
      })
      return
    }
    // 模拟提交到服务器
    wx.cloud.callFunction({
      name: 'userSubscribeFun',
      data: {
        type: 'addSubscriben', // 相当于接口地址：/addSubscriben
        params: { // 相当于调用接口的入参
          name,
          phone,
          img_path: imgPath,
          car_number: plateNumber,
          freight_type: cargoTypes[cargoIndex],
        }
      },
      complete: res => {
        if (res.result.code == 200) {
          wx.showToast({
            title: '提交成功',
          })
          wx.setStorageSync('getCodeTime', curToday)
          this.getList()
        }
        this.setData({
          name: '',
          phone: '',
          cargoIndex: null,
          imgPath: '',
          isSubmitting: false
        })
        console.log(res, '服务端响应')
      }
    })
  },

  // 手机号输入过滤
  onPhoneInput: function (e) {
    let {
      value
    } = e.detail;
    // 过滤非数字
    value = value.replace(/\D/g, '');
    // 截取前11位
    if (value.length > 11) {
      value = value.slice(0, 11);
    }
    this.setData({
      phone: value
    });
  },

  // 车牌号输入格式化
  onPlateInput: function (e) {
    let {
      value
    } = e.detail;
    // 过滤非汉字、字母和数字
    value = value.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '');

    // 自动添加分隔符
    if (value.length > 2) {
      value = value.slice(0, 2) + '·' + value.slice(2);
    }

    // 截取前8位（最多2汉字+1字母+5数字）
    if (value.length > 8) {
      value = value.slice(0, 8);
    }

    this.setData({
      plateNumber: value
    });
  },
  getphonenumber(e) {
    console.log(e);
    wx.cloud.callFunction({
      name: 'userSubscribeFun',
      data: {
        type: 'getUserPhone',
        params: {
          code: e.detail.code
        }
      },
      complete: (res) => {
        console.log(res, 123123123)
        if (res.result.code == 200) {
          this.setData({
            phone: res.result.data?.phoneNumber || ''
          })
        }
      }
    })
  },
  // 货物类型选择
  onCargoChange: function (e) {
    this.setData({
      cargoIndex: e.detail.value
    });
  },
  handleOpenFrom() {
    const getCodeTime = wx.getStorageSync('getCodeTime')
    if (getCodeTime) {
      const curToday = getTimestampToDay()
      if (curToday == getCodeTime) {
        wx.showToast({
          title: '今日已经取过号，不可重复取号',
          icon: 'none'
        })
        return
      }
    }
    this.setData({
      showList: false
    })
  },
  handleCloseFrom() {
    this.getList()
  }
});